<script lang="ts" setup>
import { bookReaderModel, IBookReader } from '@/api/borrow/borrow';
import { FormConfig } from '@/components/Form/types';
import { computed, ref, unref } from 'vue';
import ReaderSelect from '@/components/ReaderSelect/index.vue';
import { NInput } from 'naive-ui';

interface Props {
  data: Partial<IBookReader>
}
const props = defineProps<Props>();

const emits = defineEmits(['close', 'submit']);

const formData = ref<Partial<IBookReader>>({
  bookId: props.data.id,
  readerId: null,
  bookName: props.data.bookName
});

const config = computed<FormConfig<typeof formData.value>[]>(() => {
  return [
    {
      type: 'component',
      label: '借阅书籍:',
      component: NInput,
      key: 'bookName',
      props: {
        disabled: true
      }
    },
    {
      type: 'component',
      label: '读者名称:',
      component: ReaderSelect,
      key: 'readerId',
      itemProps: {
        rule: [
          { required: true, validator(rule, value) {
            if(!value) {
              return new Error('请选择读者！');
            }
            return true;
          }, trigger: 'blur' }
        ]
      }
    },
    {
      type: 'slot',
      slotName: 'submit'
    }
  ];
});

const bookReaderForm = ref();
async function submit() {
  await bookReaderForm.value.validate();
  const params = {
    ...unref(formData)
  };
  await bookReaderModel.insert(params);
  window.$message.success('操作成功！');
  emits('submit');
}
</script>
<template>
  <div>
    <Form
      ref="bookReaderForm"
      v-model:data="formData"
      :label-width="90"
      :config="config"
    >
    <template #submit>
        <div class="flex justify-end gap-mini">
          <NButton @click="emits('close')">
            取消
          </NButton>
          <NButton type="primary" @click="submit">
            确定
          </NButton>
        </div>
      </template>
    </Form>
  </div>
</template>
